package com.ezlcp.user.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ezlcp.commons.base.db.BaseDao;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.service.impl.SuperServiceImpl;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.user.entity.DicValue;
import com.ezlcp.user.enums.StatusEnum;
import com.ezlcp.user.mapper.DicValueMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * [字典值]业务服务类
 */
@Service
public class DicValueServiceImpl extends SuperServiceImpl<DicValueMapper, DicValue> implements BaseService<DicValue> {
    @Autowired
    private DicValueMapper dicValueMapper;

    @Resource
    LogService logService;
    /***
     * @description: 判断用户权限以及使用条件查询字典值列表
     * @param dicId 传入字典值id
     * @return java.util.List<com.hkyctech.loan.core.entity.DicValue> 符合要求字典值列表
     * @author Weixuan LONG
     * @date 2022/5/11 18:01
     */
    public List<DicValue> getByDicId(String dicId) {
        QueryWrapper<DicValue> wrapper = new QueryWrapper<>();
        wrapper.eq("dic_id", dicId);
        wrapper.eq("status", StatusEnum.enable.getCode());
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(tenantId)) {
            wrapper.and(query -> query.eq("is_fixed", 1).or().eq("tenant_id", tenantId));
        }
        return this.findAll(wrapper);
    }

    /***
     * @description: 判断用户权限以及使用条件查询字典值列表
     * @param dicKey 传入字典值key
     * @return java.util.List<com.hkyctech.loan.core.entity.DicValue> 符合要求字典值列表
     * @author Weixuan LONG
     * @date 2022/5/12 09:40
     */
    public List<DicValue> getByDicKey(String dicKey) {
        QueryWrapper<DicValue> wrapper = new QueryWrapper<>();
        wrapper.eq("dic_key", dicKey);
        wrapper.eq("status", StatusEnum.enable.getCode());
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(tenantId)) {
            wrapper.and(query -> query.eq("is_fixed", 1).or().eq("tenant_id", tenantId));
        }
        return this.findAll(wrapper);
    }

    /***
     * @description 根据词典Key和显示文字获取词典值
     * @param dickey key
     * @param showText 显示文字（默认为繁体中文）
     * @return com.hkyctech.loan.core.entity.DicValue
     * @author Elwin ZHANG
     * @date 2022/8/15 14:44
     */
    public DicValue getByKeyAndText(String dickey, String showText) {
        QueryWrapper<DicValue> wrapper = new QueryWrapper<>();
        wrapper.eq("dic_key", dickey);
        wrapper.eq("show_text", showText);
        wrapper.eq("status", StatusEnum.enable.getCode());
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(tenantId)) {
            wrapper.and(query -> query.eq("is_fixed", 1).or().eq("tenant_id", tenantId));
        }
        wrapper.last(" limit 1");
        return this.dicValueMapper.selectOne(wrapper);
    }

    /***
     * @description: 新增或编辑字典值
     * @param dicValueList 字典值列表
     * @return java.lang.String
     * @author Weixuan LONG
     * @date 2022/5/30 9:22
     */
    @Transactional(rollbackFor = Exception.class)
    public String saveOrUpdateDicValue(List<DicValue> dicValueList) {
        String tenantId = ContextUtil.getCurrentTenantId();
        for (DicValue dicValue : dicValueList) {
            String valId = dicValue.getValId();
            String checkNullField = checkNullField(dicValue);
            if (checkNullField.length() > 0) {
                return checkNullField;
            }
            if (StringUtils.isEmpty(tenantId)) {
                return "common.insufficientPrivileges";
            }
            if (StringUtils.isNotEmpty(valId)) {
                // 编辑操作
                DicValue oldDicValue = this.getById(valId);
                if (ObjectUtil.isNull(oldDicValue.getTenantId())) {
                    continue;
                }
                if (!oldDicValue.getTenantId().equals(tenantId)) {
                    return "common.insufficientPrivileges";
                }
                dicValue.setSeq(oldDicValue.getSeq() + 1);
                dicValue.setIsFixed((short) 0);
                this.updateById(dicValue);
                String detail = "old:" + JSON.toJSONString(oldDicValue) + "new:" + JSON.toJSONString(dicValue);
                logService.saveSystemLog("字典值", "updateDicValue", dicValue.getDicId(), detail);
            } else {
                // 新增操作
                dicValue.setTenantId(ContextUtil.getCurrentTenantId());
                dicValue.setEnText(StringUtils.defaultIfEmpty(dicValue.getEnText(),dicValue.getShowText()));
                dicValue.setHkText(StringUtils.defaultIfEmpty(dicValue.getHkText(),dicValue.getShowText()));
                dicValue.setIsFixed((short) 0);
                dicValue.setStatus(StatusEnum.enable.getCode());
                this.insert(dicValue);
                logService.saveSystemLog("字典值", "addDicValue",
                        dicValue.getDicId(), JSON.toJSONString(dicValue));
            }
        }
        return "";
    }

    /***
     * @description: 判断传参是否为空
     * @param dicValue 传入字典值
     * @return java.lang.String 当字符串长度为0，则无误；否则有误
     * @author Weixuan LONG
     * @date 2022/5/11 17:49
     */
    public String checkNullField(DicValue dicValue) {
        String dicKey = dicValue.getDicKey();
        if (ObjectUtil.isEmpty(dicValue.getSortNo())) {
            return "dicValue.inputSort";
        }
        if (StringUtils.isBlank(dicKey)) {
            return "dicValue.inputDicKey";
        }
        if (StringUtils.isBlank(dicValue.getDicId())) {
            return "dicValue.dicId";
        }
        if (StringUtils.isBlank(dicValue.getShowText())) {
            return "dicValue.showText";
        }
        return "";
    }

    /**
     * @param key   词典KEY
     * @param value save_val字段值
     * @return com.hkyctech.loan.core.entity.DicValue
     * @description: 获根据key和save_val获取(当前公司)的配置项
     * @author Elwin ZHANG
     * @date 2022/5/23 13:45
     */
    public DicValue getDicValue(String key, String value) {
        String tenantId = ContextUtil.getCurrentTenantId();
        //非公司或员工账号，先退出
        if (StringUtils.isEmpty(tenantId)) {
            return null;
        }
        QueryWrapper<DicValue> wrapper = new QueryWrapper<>();
        wrapper.eq("dic_key", key);
        wrapper.eq("tenant_id", tenantId);
        wrapper.eq("val_id", value);
        return dicValueMapper.selectOne(wrapper);
    }

    @Override
    public BaseDao<DicValue> getRepository() {
        return dicValueMapper;
    }
}